package com.ruoyi.sms.core;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.MD5;
import com.ruoyi.sms.config.properties.JXSmsProperties;
import com.ruoyi.sms.entity.JXSmsBody;
import com.ruoyi.sms.entity.JXSmsResult;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;

public class JXSmsTemplate {

    private final JXSmsProperties smsProperties;

    public JXSmsTemplate(@Autowired JXSmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }

    public JXSmsResult sendMsg(String phones, String content) {
        SimpleDateFormat timeSimpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        JXSmsBody jxSmsBody = new JXSmsBody();
        jxSmsBody.setAppKey(smsProperties.getAppKey());
        jxSmsBody.setTimestamp(System.currentTimeMillis());
        jxSmsBody.setMobile(phones);
        jxSmsBody.setContent(content);
        jxSmsBody.setSendTime(timeSimpleDateFormat.format(new Date()));
        jxSmsBody.setSign(MD5.getMD5(jxSmsBody.getAppKey() + jxSmsBody.getTimestamp() + jxSmsBody.getMobile() + jxSmsBody.getContent() + jxSmsBody.getSendTime() + smsProperties.getAppSecret()));

        HttpRequest post = HttpUtil.createPost(smsProperties.getEndpoint() + smsProperties.getUri());
        post.contentType("application/json");
        post.charset("utf-8");
        post.body(JSONObject.toJSONString(jxSmsBody));
        String body = post.execute().body();
        return JSONObject.parseObject(body, JXSmsResult.class);
    }
}
